//
//  ZZComposeView.swift
//  web
//
//  Created by 张卓 on 2017/2/8.
//  Copyright © 2017年 ZZ. All rights reserved.
//

import UIKit
import pop

class ZZComposeView: UIView {
    
    //保存 6 个按钮的数组
    var composeButtonArr : [ZZComposeButton] = [ZZComposeButton]()
//    //保存6 个按钮的模型数组
//    var composeModelArr : [ZZComposeModel] = [ZZComposeModel]()
    //记录mainvc
    var target:UIViewController?
    
    //MARK: - 供外界调用的方法
    func show(target:UIViewController){
        self.target = target
        //添加composeView -> mainVC.view
        target.view.addSubview(self)
        //设置6个按钮动画
        setupComposeBntAnim(isUp: true)
        
    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        backgroundColor = ZZRandomColor()
        //设置size
        self.frame.size = CGSize(width: ZZSCREENW, height: ZZSCREENH)
        
        //添加控件
        addSubview(bgImgView)
        addSubview(logImgView)
        //设置约束
        bgImgView.snp_makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        logImgView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        addClickBtn()
        
    }
    
    //MARK: - 设置6个按钮动画
    private func setupComposeBntAnim(isUp:Bool){
        // 默认动画使用高度临界值
        var H : CGFloat = 350
        //让按钮消失
        if !isUp{
            composeButtonArr.reverse()
            H = -350
        }
        
        for (i,button) in composeButtonArr.enumerated(){
         
            //实例化阻尼动画
            let anSpring = POPSpringAnimation(propertyNamed: kPOPViewCenter)!
            //设置终点位置
            anSpring.toValue = CGPoint(x: button.center.x, y: button.center.y - H)
            // 开始时间  CACurrentMediaTime 系统绝对时间
            anSpring.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //弹力越大 则震动越大
            anSpring.springBounciness = 4
            anSpring.springSpeed = 12
            //给button按钮添加动画
            button.pop_add(anSpring, forKey: nil)
            
        }
    }
    
    
    //MARK: - 创建 6 个按钮
    private func addClickBtn() {
        //得到数组
        let composeModelArr = loadPlist()
        //抽取按钮的高度和宽度
        let buttonW :CGFloat = 80
        let buttonH :CGFloat = 110
        //计算间距
        let buttonMargin = (ZZSCREENW - buttonW*3) / 4
        //遍历数组
        for (i,buttonModel) in composeModelArr.enumerated(){
            //实例化button 
            let button = ZZComposeButton()
//            button.tag = 1
            //设置model
            button.composeModel = buttonModel
            //添加点击事件
            button.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
            //设置size
            button.frame.size = CGSize(width: 80, height: 110)
            // 计算列和行的索引
            let colIndex = CGFloat(i%3)
            let rowIndex = CGFloat(i/3)
            //设置X  Y 轴
            button.frame.origin.x = buttonMargin + colIndex * (buttonW + buttonMargin)
            button.frame.origin.y = rowIndex * (buttonH + buttonMargin) + ZZSCREENH
            //设置image
            button.setImage(UIImage(named:buttonModel.icon ?? ""), for: UIControlState.normal)
            button.setTitle(buttonModel.title, for: UIControlState.normal)
            addSubview(button)
            
            composeButtonArr.append(button)
        }
        
    }
    
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        removeFromSuperview()
        setupComposeBntAnim(isUp: false)
        //移除
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25) {
            self.removeFromSuperview()
        }
    }

    //MARK: - 懒加载控件
    private lazy var bgImgView : UIImageView = {
        let img = UIImageView()
        img.image = UIImage.screenShot()!.applyExtraLightEffect()
        return img
    }()
    
    //LOG
    private lazy var logImgView : UIImageView = UIImageView(imgName: "compose_slogan")
    
}

extension ZZComposeView{
    //MARK: - 加载Plist 文件
    func loadPlist()->[ZZComposeModel] {
        //获取路径
        let file = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        //获取plistArray
        let plistArr = NSArray(contentsOfFile: file)!
        //字典转模型
        let tempArr = NSArray.yy_modelArray(with: ZZComposeModel.self, json: plistArr)
        
        return tempArr as! [ZZComposeModel]
    }
}
//MARK: - 监听按钮点击时间
extension ZZComposeView{
    func buttonClick(bnt:ZZComposeButton){
        
        //设置按钮放大和缩小
        UIView.animate(withDuration: 0.25, animations: {
            //遍历6个按钮数组
            for button in self.composeButtonArr {
                // 透明度设置为0
                button.alpha = 0
                //判断是否是点击的按钮
                if bnt == button{
                    //放大操作
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    //缩小操作
                    button.transform = CGAffineTransform(scaleX: 0, y: 0)
                }
            }
        }) { (_) in
            //遍历6个按钮
            UIView.animate(withDuration: 0.25, animations: {
                for button in self.composeButtonArr {
                    //透明度设置为1
                    button.alpha = 1
                    //把所有按钮恢复成原样
                    button.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                
                
                //通过模型中的classname得到对应的class
//                let clas = NSClassFromString(bnt.composeModel?.classname ?? "")! as! UIViewController.Type
                let clas = NSClassFromString(bnt.composeModel?.classname ?? "")! as! UIViewController.Type
                // 通过class实例化一个控制器的对象
                let vc = clas.init()
                //导航控制器
                let composeNav = ZZNavViewController(rootViewController: vc)
                //模态
                self.target?.present(composeNav, animated: true, completion: { 
                    //移除当前视图
                    self.removeFromSuperview()
                    
                })
                
                
                
            })
        
        }
    }
}
